package com.saifan.wyy_ov.ui.onlishop;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.IconText;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.CommonDataBean;
import com.saifan.wyy_ov.data.bean.GoodsBean;
import com.saifan.wyy_ov.data.bean.GoodsType;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.SoftUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import java.util.ArrayList;
import java.util.List;

import lomasky.ma.xui.SpinnerAdapter;

/**
 * @author WangLi
 * @version V1.0
 * @date 2015年3月18日 下午1:07:05
 * @Description 店铺其它商品页面
 */

public class OtherGoodsActivity extends BaseActivity implements SearchView.OnQueryTextListener {
    private ListView listView;
    private RelativeLayout loadlay;


    private IGetData getData;
    private CommonDataBean requestBean;
    private List<GoodsBean> list;
    private int page = 0;
    private CommonAdapter<GoodsBean> adapter;
    private List<GoodsType> types;


    private SearchView searchView;
    private boolean serarchFlag = false;
    private String searchName = "";
    private String storeId = "";

    private Toolbar toolbar;
    private RefreshLayout refreshLayout;
    private ListPopupWindow listPopupWindow;
    private android.support.v7.widget.AppCompatSpinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_goods);


        storeId = getIntent().getStringExtra("storeId");
        requestBean = new CommonDataBean();
        requestBean.setID(getIntent().getIntExtra("ID", -1));

        findViews();
        initPopList();
        getData = new GetData();
        getDataInit();
//        getGoodsType();
    }

      void initPopList() {
        listPopupWindow = new ListPopupWindow(this);
        lomasky.ma.xui.CommonAdapter adapter = new lomasky.ma.xui.CommonAdapter<IconText>(this, R.layout.pop_item) {
            @Override
            public void onBind(lomasky.ma.xui.ViewHolderHelper holder, IconText iconText, int i) {
                holder.setImage(R.id.pop_img, iconText.icon);
                holder.setText(R.id.pop_text, iconText.text);
            }
        };
        List<IconText> list = new ArrayList<>();
        list.add(new IconText(R.mipmap.home_insidepage, "商城首页"));
        list.add(new IconText(R.mipmap.cart_insidepage, "我的购物车"));
        list.add(new IconText(R.mipmap.indent_insidepage, "我的订单"));
        list.add(new IconText(R.mipmap.collect_insidepage, "我的收藏"));
        adapter.setData(list);

        listPopupWindow.setAdapter(adapter);
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = null;
                switch (position) {
                    case 0:
                        intent = new Intent(getBaseContext(), OnlineShopActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        break;
                    case 1:
                        intent = new Intent(getBaseContext(), MyCartActivity.class);
                        break;
                    case 2:
                        intent = new Intent(getBaseContext(), MyOrderActivity.class);
                        break;
                    case 3:
                        intent = new Intent(getBaseContext(), MyCollectActivity.class);
                        break;
                    default:
                        break;
                }
                listPopupWindow.dismiss();
                if (intent != null) {
                    startActivity(intent);
                }


            }
        });

    }

    @SuppressLint("NewApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.common_details, menu);
        // 对搜索监听
        MenuItem searchItem = menu.findItem(R.id.menu_search);
		searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
//        searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        if (searchView!=null){
            searchView.setOnQueryTextListener(this);
        }

        getWindow().getWindowManager().getDefaultDisplay().getWidth();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_cart) {

                listPopupWindow.setAnchorView(toolbar);
                listPopupWindow.setWidth(lomasky.ma.utils.DensityUtil.getWidth(this) / 2);
                listPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                listPopupWindow.setHorizontalOffset(lomasky.ma.utils.DensityUtil.getWidth(this) / 2);
                listPopupWindow.show();
            return true;


        }


        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onQueryTextChange(String arg0) {
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String arg0) {
        SoftUtil.hideSoftInput(OtherGoodsActivity.this, searchView);
        searchName = arg0;
        list.clear();

        loadlay.setVisibility(View.VISIBLE);
        serarchFlag = true;
        getSearchData();
        return true;
    }

    // 初始化控件
    @SuppressLint("InflateParams")
    private void findViews() {
        loadlay = (RelativeLayout) findViewById(R.id.loading_lay);
        listView = (ListView) findViewById(R.id.listView);
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
//        this.spinner = (AppCompatSpinner) findViewById(R.id.spinner);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//                if (list.get(arg2).isIsGroupBuying()){
//                    Intent intent = new Intent(OtherGoodsActivity.this, GroupBuyDetailsActivity.class);
//                    intent.putExtra("storeId", storeId);
//                    intent.putExtra("goodsId", list.get(arg2).getID());
//                    intent.putExtra("goodsName", list.get(arg2).getGoodsName());
//                    intent.putExtra("price", list.get(arg2).getGoodsPrice());
//                    startActivity(intent);
//                }else if (list.get(arg2).isIsIsSalesPromotion()){
//                    Intent intent = new Intent(OtherGoodsActivity.this, GoodsDetailActivity.class);
//                    intent.putExtra("storeId", storeId);
//                    intent.putExtra("goodsId", list.get(arg2).getID());
//                    intent.putExtra("goodsName", list.get(arg2).getGoodsName());
//                    intent.putExtra("price", list.get(arg2).getGoodsPrice());
//                    startActivity(intent);
//
//                }else {
//                    Intent intent = new Intent(OtherGoodsActivity.this, GoodsDetailActivity.class);
//                    intent.putExtra("storeId", storeId);
//                    intent.putExtra("goodsId", list.get(arg2).getID());
//                    intent.putExtra("goodsName", list.get(arg2).getGoodsName());
//                    intent.putExtra("price", list.get(arg2).getGoodsPrice());
//                    startActivity(intent);
//                }


                Intent intent = new Intent(OtherGoodsActivity.this, GoodsDetailActivity.class);
                intent.putExtra("storeId", storeId);
                intent.putExtra("goodsId", list.get(arg2).getID());
                intent.putExtra("goodsName", list.get(arg2).getGoodsName());
                intent.putExtra("price", list.get(arg2).getGoodsPrice());
                startActivity(intent);

            }
        });
        list = new ArrayList<GoodsBean>();
        adapter = new CommonAdapter<GoodsBean>(OtherGoodsActivity.this, list, R.layout.goods_item) {
            @Override
            public void convert(ViewHolderHelper helper, GoodsBean item) {
                helper.setImageByUrl(R.id.goods_img, item.getCoverPhoto());
                helper.setText(R.id.goods_name, item.getGoodsName());
                helper.setText(R.id.goods_category, "类别: " + item.getGoodsType());
                helper.setText(R.id.goods_price, "店铺价: " + item.getGoodsPrice());
                helper.setText(R.id.sales, "已售" + item.getSold());
            }
        };
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // TODO Auto-generated method stub
                page = 0;
                refreshLayout.setRefreshing(true);
                getDataInit();
            }
        });

        refreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                // TODO Auto-generated method stub
                refreshLayout.setLoading(true);
                page++;
                getDataInit();

            }
        });
        listView.setAdapter(adapter);
        // 顶部操作栏


    }

    // 获取商品列表
    private void getDataInit() {
        requestBean.setPage(page);
        if (page < 1) {
            loadlay.setVisibility(View.VISIBLE);
        }
//        if (leftOperateTextView.getText().toString().equals("全部")) {
//            requestBean.setGoodsType("");
//        } else {
//            requestBean.setGoodsType(leftOperateTextView.getText().toString());
//        }
//        requestBean.setType(rightTypeList.indexOf(rightOperateTextView.getText().toString()));
        getData.getDataJson(OtherGoodsActivity.this, Api.StoreList.GOODSLIST, requestBean, "", new ResponseData() {

            @Override
            public void onSuccess(String json) {



                List<GoodsBean> data = (new Gson()).fromJson(json, new TypeToken<List<GoodsBean>>() {
                }.getType());
                if (data.size() > 0) {
                    if (page == 0) {
                        list = data;

                    } else {
                        list.addAll(data);
                    }
                } else {
                    if (page == 0) {
                        ToastUtil.showToast(OtherGoodsActivity.this, "暂无商品信息");
                    } else {
                        ToastUtil.showToast(OtherGoodsActivity.this, "暂无更多商品信息");
                        page--;
                    }
                }
                adapter.mDatas = list;
                adapter.notifyDataSetChanged();
                loadlay.setVisibility(View.GONE);
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);


            }

            @Override
            public void onFailed(String str) {
                loadlay.setVisibility(View.GONE);
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                if (page >0) {
                    page--;
                }

            }
        });
    }

    // 获取商品分类
//    private void getGoodsType() {
//        getData.getDataJson(OtherGoodsActivity.this, Api.StoreList.GOODSTYPE, requestBean, "", new ResponseData() {
//
//            @Override
//            public void onSuccess(String json) {
//                types = new ArrayList<GoodsType>();
//                GoodsType type = new GoodsType();
//                type.setTypeName("全部");
//                types.add(type);
//                List<GoodsType> dataList = (new Gson()).fromJson(json, new TypeToken<List<GoodsType>>() {
//                }.getType());
//                types.addAll(dataList);
//
//                List<String> typesString= new ArrayList<String>();
//                for (GoodsType o: types){
//                    typesString.add(o.getTypeName());
//                }
//                spinner.setAdapter(new SpinnerAdapter(OtherGoodsActivity.this,typesString));
//
//
//
//
//            }
//
//            @Override
//            public void onFailed(String str) {
//            }
//        });
//    }



    //获取搜索结果
    private void getSearchData() {
        requestBean = new CommonDataBean();
        requestBean.setPage(page);
        if (page == 0) {
            loadlay.setVisibility(View.VISIBLE);
        }
        requestBean.setID(getIntent().getIntExtra("ID", -1));
        requestBean.setGoodsName(searchName);
        getData.getDataJson(OtherGoodsActivity.this, Api.StoreList.GOODSLIST, requestBean, "", new ResponseData() {

            @Override
            public void onSuccess(String json) {

                List<GoodsBean> data = new Gson().fromJson(json, new TypeToken<List<GoodsBean>>() {
                }.getType());
                if (data!=null&&!data.isEmpty()) {
                    if (page == 0) {
                        list = data;

                    } else {
                        list.addAll(data);
                    }
                    adapter.mDatas = list;
                    adapter.notifyDataSetChanged();
                } else {
                    if (page == 0) {
                        ToastUtil.showToast(OtherGoodsActivity.this, "暂无商品信息");
                    } else {
                        ToastUtil.showToast(OtherGoodsActivity.this, "暂无更多商品信息");
                        page--;
                    }
                }
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                loadlay.setVisibility(View.GONE);

            }

            @Override
            public void onFailed(String str) {
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                loadlay.setVisibility(View.GONE);
                if (page > 0) {
                    page--;
                }

            }
        });
    }
}
